package com.yonyou.cyxdms.basedata.client.service.basedata;

import com.yonyou.cyx.framework.bean.dto.base.ClientInfoDTO;
import com.yonyou.cyx.framework.bean.dto.framework.RestResultResponse;
import com.yonyou.cyx.framework.compent.redis.RedisClient;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.ServiceBizException;
import com.yonyou.cyx.function.utils.common.CommonUtils;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.basedata.client.constants.BaseDataCommonConstants;
import com.yonyou.cyxdms.basedata.client.domains.vo.BrandCacheVO;
import com.yonyou.cyxdms.basedata.client.domains.vo.VehicleVO;
import com.yonyou.cyxdms.basedata.client.feign.BaseDataCommonClient;
import com.yonyou.cyxdms.basedata.client.util.ConditionMapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

/**
 * 品牌信息
 *
 * @author: renwd
 * @since: 2018/11/27
 * @version:1.0 Copyright: Copyright (c) 2018
 */

@Service
public class BaseCommonBrandServiceImpl implements BaseCommonBrandService {

    private final Logger logger = LoggerFactory.getLogger(BaseCommonBrandServiceImpl.class);

    @Autowired
    private BaseDataCommonClient baseDataCommonClient;

    @Autowired
    private RedisClient redisClient;

    /**
     * 根据品牌id查询品牌信息
     *
     * @param brandId
     * @return com.yonyou.cyxdms.basedata.client.domains.vo.BrandCacheVO
     * @author renwd
     * @since 2019/9/10
     */
    @Override
    public BrandCacheVO getValueByBrandId(String brandId) {
        ClientInfoDTO loginInfoDto = ApplicationContextHelper.getBeanByType(ClientInfoDTO.class);
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.BRAND_CACHE_BRANDID, loginInfoDto.getAppId());
        Object brandDto = redisClient.hget(messageFormat, brandId);
        if (null == brandDto) {
            // 查询所有数据
            loadValueIfNotExists(ConditionMapUtils.conditionMap(loginInfoDto.getAppId(), null), messageFormat);
            Object redisBrandDto = redisClient.hget(messageFormat, brandId);
            if (null == redisBrandDto) {
                return null;
            }
            return JSONUtil.jsonToObj(JSONUtil.objectToJson(redisBrandDto), BrandCacheVO.class);
        } else {
            return JSONUtil.jsonToObj(JSONUtil.objectToJson(brandDto), BrandCacheVO.class);
        }
    }



    /**
     * 查询数据
     *
     * @param queryByMap
     * @author renwd
     * @since 2018/11/27
     */
    private void loadValueIfNotExists(Map<String, Object> queryByMap, String messageFormat) {
        List<BrandCacheVO> brandDtoResponse = baseDataCommonClient.queryBrandBySql(queryByMap).getData();
//        logger.info("feign查询Brand信息:{}", brandDtoResponse);

        if (!CommonUtils.isNullOrEmpty(brandDtoResponse)) {
            brandDtoResponse.stream().forEach(brandCacheDto -> initOneValue(brandCacheDto, messageFormat));
        }
    }

    /**
     * 将数据放置redis，将ownerCode是-1的数据也放置在传入的ownerCode下
     *
     * @param brandCache
     * @param key
     * @author renwd
     * @since 2018/11/27
     */
    private void initOneValue(BrandCacheVO brandCache, String key) {
        redisClient.hsetExpire(key, String.valueOf(brandCache.getBrandId()), JSONUtil.objectToJson(brandCache), BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
    }

    /**
     * 查询租户下的经销商下的所有品牌
     *
     * @return java.util.List<com.yonyou.cyxdms.basedata.client.domains.vo.BrandCacheVO>
     * @author renwd
     * @since 2019/9/10
     */
    @Override
    public List<BrandCacheVO> listAllBrand() {
        ClientInfoDTO loginInfoDto = ApplicationContextHelper.getBeanByType(ClientInfoDTO.class);
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.BRAND_CACHE_BRAND_ALL, loginInfoDto.getAppId(), loginInfoDto.getOwnerCode());
        Object brandDto = redisClient.get(messageFormat);
        if (null == brandDto) {
            // 查询所有数据
            List<BrandCacheVO> brandDtoResponse = baseDataCommonClient.queryBrandBySql(ConditionMapUtils.conditionMap(loginInfoDto.getAppId(), loginInfoDto.getOwnerCode())).getData();
//            logger.info("feign查询Brand信息:{}", brandDtoResponse);

            if (!CommonUtils.isNullOrEmpty(brandDtoResponse)) {
                redisClient.set(messageFormat, JSONUtil.objectToJson(brandDtoResponse), BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
            }
            Object redisBrandDto = redisClient.get(messageFormat);
            if (null == redisBrandDto) {
                return null;
            }
            return JSONUtil.jsonToList(JSONUtil.objectToJson(redisBrandDto), BrandCacheVO.class);
        } else {
            return JSONUtil.jsonToList(JSONUtil.objectToJson(brandDto), BrandCacheVO.class);
        }
    }

    /**
     * 根据条件查询品牌，车系，车型，配置id列表
     *
     * @param searchCondition
     * @return com.yonyou.cyxdms.basedata.client.domains.vo.VehicleVO
     * @author dengqiang
     * @since 2019/9/17
     */
    @Override
    public VehicleVO getIdListByCondition(String searchCondition) {
        RestResultResponse<VehicleVO> result = baseDataCommonClient.getIdListByCondition(searchCondition);
        if (result.getResultCode() == 200) {
            return result.getData();
        } else {
            throw new ServiceBizException("根据条件查询品牌，车系，车型，配置id列表");
        }
    }

    /**
     * 未登陆获取全品牌
     *
     * @param:
     * @return:
     * @auther: tanjie
     * @since: 2019/11/4
     */
    @Override
    public List<BrandCacheVO> getAllBrandByAppId(String appId) {
        String messageFormat = MessageFormat.format(BaseDataCommonConstants.BRAND_CACHE_BRAND_APPID_ALL, appId);
        //ClientInfoDTO loginInfoDto = ApplicationContextHelper.getBeanByType(ClientInfoDTO.class);
        Object brandDto = redisClient.get(messageFormat);
        if (null == brandDto) {
            // 查询所有数据
            List<BrandCacheVO> brandDtoResponse =
                    baseDataCommonClient.getAllBrandByAppId(appId).getData();
//            logger.info("feign查询Brand信息:{}", brandDtoResponse);
            if (!CommonUtils.isNullOrEmpty(brandDtoResponse)) {
                redisClient.set(messageFormat, JSONUtil.objectToJson(brandDtoResponse),
                        BaseDataCommonConstants.EXPIRE_TIME_ONE_DAY);
            }
            Object redisBrandDto = redisClient.get(messageFormat);
            if (null == redisBrandDto) {
                return null;
            }
            return JSONUtil.jsonToList(JSONUtil.objectToJson(redisBrandDto), BrandCacheVO.class);
        } else {
            return JSONUtil.jsonToList(JSONUtil.objectToJson(brandDto), BrandCacheVO.class);
        }
    }

}
